<template>
    <a-drawer
      class="drawer-wrapper"
      title="导入已有项目计划"
      placement="right"
      width="1129"
      :closable="false"
      :visible="dialogVisible"
      :after-visible-change="afterVisibleChange"
      @close="cancel"
    >
      <div class="drawer-content">
        <div class="title-box">
          <span>项目列表</span>
          <global-search :searchTableData="searchData" @onSearch="onSearch"></global-search>
          <!-- <a-input-search placeholder="请输入" style="width: 224px" /> -->
        </div>
        <a-spin :spinning='submitDiabled' class='main-table'>
          <common-table
            ref="table"
            :columns="columns"
            :tableData="tableData"
            :selectType="'radio'"
            data-row-key="oid"
            :clickRowSelect="true"
            :isRowsSelectVisible="isRowsSelectVisible"
            :loadVisible="loadVisible"
            :hasAttention="hasAttention"
            scrollY='100%'
            :this-table-name="'porjectManageList'"
            :this-table-header-data="thisTableHeaderData"
            :this-table-header-data-middel="thisTableHeaderDataMiddel"
            @selectedRows="selectedRows"
            @clickRow="clickRow"
          ></common-table>
        </a-spin>
      </div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="cancel">
          取消
        </a-button>
        <a-button type="primary" :disabled="submitDiabled" @click="submit">
          确定
        </a-button>
      </div>
    </a-drawer>
</template>
<script>
import globalSearch from "@/components/common/globalSearch"
import commonDialog from '@/components/common/commonDialog'
import commonTable from "@/components/common/commonTable";
import {
  getProjectList, 
  getProjectCaches
} from "@/api/projectManage.js"
import { importOtherProjectPIPlan } from '@/api/projectPlan.js'
import _ from 'lodash'
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
// userId: userinfo.loginName
const columns = [
  {
    name: 'projectname',
    displayName: '项目名称',
    key: 'projectname',
    fieldType: 'Input',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '项目级别',
    name: 'importantgrade',
    key: 'importantgrade',
    fieldType: 'Select',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '项目经理',
    key: 'projectmananger',
    name: 'projectmananger',
    fieldType: 'Select',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '所属研究所',
    key: 'projectgroupreference',
    fieldType: 'Input',
    name: 'projectgroupreference',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    displayName: '项目大类',
    key: 'projecttype',
    fieldType: 'Select',
    dataType: 'String',
    name: 'projecttype',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  },
  {
    key: 'projectsmalltype',
    displayName: '细分类型',
    name: 'projectsmalltype',
    fieldType: 'Input',
    dataType: 'String',
    scopedSlots: {
      filterDropdown: "filterDropdown",
      filterIcon: "filterIcon",
      customRender: "customRender"
    }
  }
]
export default {
  components: { globalSearch, commonDialog, commonTable },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
       /**表格操作参数 */
      isRowsSelectVisible: true, // 是否显示表格的选择列
      columns: columns,
      defaultTagId: 'ALL',
      tableData: [
        // {}
      ],
      searchData: [],
      loadVisible: false,
      hasSelectTableData: [], // 表格已选中数据
      hasAttention: [], // 已关注数据
      thisTableHeaderData: [],//当前表格所有表头数据
      thisTableHeaderDataMiddel: [],//当前表格存在中台的表头数据
      oid: '',
      submitDiabled: false
    }
  },
  computed: {
    
  },
  watch: {
    dialogVisible(val) {
      if (val && this.$refs.table) {
        this.$refs.table.selectedRowKeys = [] // 讲选中的置空
      }
    }
  },
  mounted() {
      this.getTableDataParams('ALL')
      this.oid = sessionStorage.getItem('oid')
  },
  methods: {
    // 全局搜索
    onSearch(tableVal, searchValue) {
      this.loadVisible = true
      if (!searchValue) {
        // 当传过来的数据为空，并且输入条件为空时，重新调用
        this.getTableDataParams(this.defaultTagId)
      } else {
        this.loadVisible = false
        this.tableData = tableVal
      }
    },
    submit() {
      if (!this.hasSelectTableData.length) {
        this.$message.error('请选择一行数据')
      } else {
        let params = {
          userId: userinfo.loginName,
          sourceOid: `OR:com.pisx.pmgt.project.PIProject:${this.hasSelectTableData[0].oid}`,
          targetOid: `OR:com.pisx.pmgt.project.PIProject:${this.oid}`
        }
        this.submitDiabled = true
        importOtherProjectPIPlan(params).then(({data}) => {
          this.submitDiabled = false
          if (data.success === "false") {
           this.$message.info(data.message || '导入失败')     
          } else {
            this.$message.info(data.message)
          }
          this.$emit('ok', data.success === "true")
        })
      }
    },
    getTableDataParams(tabType) {
      this.loadVisible = true
      if (!this.addTabDrawerVisible) {
        this.tableData = []
      }
      let data = {
        "type": tabType
      }
      getProjectList(data).then(res => {
        if (res && res.status === 200) {
          if (res.data && res.data.data && res.data.data.length > 0) {
            let arr = res.data.data
            this.getTableData(arr)
          } else {
            this.loadVisible = false
            this.tableData = []
          }
        } else {
          this.tableData = []
        }
      });
    },
    getTableData(paramsData) {
      getProjectCaches(paramsData).then(res => {
        if (res.status === 200) {
          if (res.data && res.data.length > 0) {
            
            // 去除当前项目
            const newPlanIndex = res.data.findIndex(item => item.oid === this.oid)
            res.data.splice(newPlanIndex, 1)
            let importantgradeFilter = [], projectmanangerFilter = [], projectTypeFilter = []
            res.data.map(item => {
              if (item.importantGrade && !importantgradeFilter.includes(item.importantGrade)) {
                importantgradeFilter.push(item.importantGrade)
              }
              if (item.projectMananger && !projectmanangerFilter.includes(item.projectMananger)) {
                projectmanangerFilter.push(item.projectMananger)
              }
              if (item.projectType && !projectTypeFilter.includes(item.projectType)) {
                projectTypeFilter.push(item.projectType)
              }
              // 先全部转化为大写，然后再转化为小写(因为返回的字段中有全部是小写的情况)
              for (var key in item) {
                item[key.toUpperCase()] = item[key];
                delete (item[key]);
              }
            })
            res.data.map(it => {
              // 先全部转化为大写，然后再转化为小写
              for (var key in it) {
                it[key.toLowerCase()] = it[key];
                delete (it[key]);
              }
            })
            // this.tableData = res.data
            this.tableData = _.orderBy(res.data, ['createstamp'], ['desc'])//按照创建时间降序排序
            let searchData = []
            res.data.forEach(item => {
              let rowData = {}
              rowData['oid'] = item.oid
              this.columns.forEach(column => {
                rowData[column.key] = item[column.key]
              })
              searchData.push(rowData)
            })
            this.searchData = _.orderBy(searchData, ['createstamp'], ['desc'])//按照创建时间降序排序
            this.loadVisible = false
            // console.log(this.searchData)
            this.columns[1].fieldValue = importantgradeFilter
            this.columns[2].fieldValue = projectmanangerFilter
            this.columns[4].fieldValue = projectTypeFilter
          }
        } else {
          this.searchData = []
          this.loadVisible = false
          this.$message.error('获取数据失败')
        }
      }).catch(error => {
        this.searchData = []
        this.loadVisible = false
        this.$message.error('获取数据接口异常')
      })
    },
    // 选中数据
    selectedRows(val) {
      this.hasSelectTableData = val
    },
    clickRow(val) {
      this.hasSelectTableData = val
    },
    cancel() {
      this.$emit('cancel')
    },
    afterVisibleChange(val) {
      // console.log('visible', val);
    },
  }
}
</script>
<style lang="less" scoped>
  .drawer-wrapper{
    /deep/ .ant-drawer-header{
      padding: 13px 21px;
      .ant-drawer-title{
        line-height: 24px;
        color: #333;
      }
    }
    .drawer-content{
      .title-box{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      /deep/ .ant-table-body{
        min-height: calc(100vh - 310px);
      }
      /deep/ .ant-table-placeholder{
        min-height: calc(100vh - 322px);
        margin-top: -420px;
        border: none;
      }
    }
  }
</style>